package com.xtaller.easy.admin.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.xtaller.common.bean.JWTResult;
import com.xtaller.common.bean.Where;
import com.xtaller.common.convert.W;
import com.xtaller.common.kit.JwtKit;
import com.xtaller.easy.admin.base.TApi;
import com.xtaller.easy.admin.config.R;
import com.xtaller.easy.admin.model.VLog;
import com.xtaller.easy.admin.service.impl.SysLogService;
import com.xtaller.easy.admin.service.impl.VLogService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Taller on 2018/5/13
 */
@Api(tags = "日志管理api")
@RestController
@RequestMapping("/v1/sys")
@CrossOrigin   //跨域服务注解
public class LogApi extends TApi {
    @Autowired
    private VLogService logService;
    @Autowired
    private SysLogService sysLogService;

    @GetMapping("/log/{index}-{size}-{type}-{loginName}")
    @ApiOperation(value = "读取日志")
    public Object getLog(@ApiParam("当前页码") @PathVariable("index") int index,
                         @ApiParam("每页显示条数") @PathVariable("size") int size,
                         @ApiParam("类型") @PathVariable("type") int type,
                         @ApiParam("登录名") @PathVariable("loginName") String loginName
                         ){

        List<Where> wheres = W.f(
                W.and("type", "eq", type),
                W.and("loginName", "like", loginName)
        );
        return R.ok(data2Grid(logService.page(index, size, wheres)));
    }

    @PostMapping("/log")
    @ApiOperation(value = "解析Token")
    public Object readToken(@RequestBody JSONObject jwt){
        JWTResult jwtResult = JwtKit.validateJWT(jwt.getString("token"));
        if (jwtResult.isSuccess()) {
            Claims claims = jwtResult.getClaims();
            return R.ok("解析成功", claims);
        }else {
            return R.ok("解析失败", new JSONObject());
        }
    }

    @GetMapping("/log-api/{day}")
    @ApiOperation(value = "读取日志")
    public Object getLog(@PathVariable("day") int day){
        return R.ok(sysLogService.getApiLog(day));
    }
    @GetMapping("/log-count")
    @ApiOperation(value = "读取日志")
    public Object getCount(){
        return R.ok(sysLogService.getCount());
    }
}
